package com.eduagent.xwqeduagent.tools;

import com.eduagent.xwqeduagent.app.agent.OnlineSearch;
import com.eduagent.xwqeduagent.model.vo.OnlineSearchResultVO;
import com.eduagent.xwqeduagent.model.vo.SearchResultItemVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

/**
 * 基于Coze API的联网搜索工具
 * 通过Spring AI框架提供联网搜索功能，支持结构化搜索结果解析
 */
@Slf4j
@RequiredArgsConstructor
public class WebSearchCozeTool {
    
    private final OnlineSearch onlineSearch;

    @Tool(description = "Perform online search using Coze API with structured results parsing. " +
                       "This tool can search for real-time information from the internet and return " +
                       "structured search results including source websites, descriptions, and links.")
    public String searchOnline(
            @ToolParam(description = "Search query content - what you want to search for") 
            String searchContent) {
        
        // 生成一个会话ID用于本次搜索
        String sessionId = "tool_search_" + System.currentTimeMillis();
        String userId = "spring_ai_tool";
        
        log.info("Spring AI工具开始联网搜索，内容：{}", searchContent);
        
        try {
            // 调用联网搜索服务
            OnlineSearchResultVO result = onlineSearch.performOnlineSearch(searchContent, userId, sessionId);
            
            if ("success".equals(result.getStatus())) {
                // 格式化搜索结果为易读的字符串
                return formatSearchResult(result);
            } else {
                return "搜索失败：" + result.getMessage();
            }
        } catch (Exception e) {
            log.error("Spring AI工具联网搜索异常", e);
            return "搜索出现异常：" + e.getMessage();
        }
    }

    /**
     * 格式化搜索结果为AI易理解的文本格式
     * @param result 搜索结果对象
     * @return 格式化后的文本
     */
    private String formatSearchResult(OnlineSearchResultVO result) {
        StringBuilder sb = new StringBuilder();
        
        sb.append("联网搜索完成！搜索内容：").append(result.getSearchContent()).append("\n");
        sb.append("找到 ").append(result.getResultCount()).append(" 个相关结果：\n\n");
        
        // 格式化每个搜索结果项
        if (result.getSearchItems() != null && !result.getSearchItems().isEmpty()) {
            for (SearchResultItemVO item : result.getSearchItems()) {
                sb.append("【").append(item.getIndex()).append("】来源：").append(item.getSourceName()).append("\n");
                sb.append("内容：").append(item.getDescription()).append("\n");
                sb.append("链接：").append(item.getUrl()).append("\n");
                if (item.getLinkText() != null) {
                    sb.append("标题：").append(item.getLinkText()).append("\n");
                }
                sb.append("\n");
            }
        } else {
            // 如果没有结构化结果，使用原始搜索结果
            sb.append("搜索结果：\n").append(result.getSearchResult()).append("\n");
        }
        
        sb.append("\n搜索时间：").append(result.getSearchTime());
        
        return sb.toString();
    }
}
